#include "head.h"
#include "macro.h"
#include "log.h"
#include "config.h"

CConfig::CConfig(const char* psFile)
{
	memset(m_sfile, 0, sizeof(m_sfile));
	strncpy(m_sfile, psFile, 128);
}

CConfig::CConfig()
{

}
CConfig::~CConfig()
{

}

int CConfig::LoadConfig(const char* psFile)
{
	m_fin.open(psFile);
	if (!m_fin)
	{
		LOG_PRINT_DEBUG("Open config file error  filename = " << psFile);
		return PUB_ERROR;
	}

	element(m_fin);
	m_fin.close();
	return PUB_OK;
}
int CConfig::LoadConfig()
{
	m_fin.open(m_sfile);
	if (!m_fin)
	{
		return PUB_ERROR;
	}
	element(m_fin);
	m_fin.close();
	return PUB_OK;
}

void CConfig::trim_left(string& str)
{
	string::size_type pos = str.find_first_not_of(" \t\r\n");
	if (pos != string::npos && pos != 0)
	{
		str.erase(0, pos);
	}
}
void CConfig::trim_right(string& str)
{
	string tmp(str);
	string::size_type pos = tmp.find_last_not_of(" \t\r\n");
	if (pos != string::npos)
	{
		str.erase(pos + 1);
	}
}

void CConfig::element(ifstream& fin)
{
	string sline;
	string skey;
	ITEM item;
	while (getline(fin, sline))
	{
		trim_left(sline);
		trim_right(sline);

		if (sline.size() == 0 || sline[0] == '#')
		{
			continue;
		}

		if (sline[0] == '[')
		{
			if (skey.size() != 0)
			{
				m_doc[skey] = item;
				item.erase(item.begin(), item.end());
			}
			trim_left(sline);
			trim_right(sline);
			skey = sline.substr(sline.find_first_of("[") + 1,
					sline.find_last_of("]") - 1);
			continue;
		}
		else
		{
			size_t pos = sline.find_first_of("=");
			if (pos != string::npos)
			{
				string key = sline.substr(0, pos - 1);
				trim_left(key);
				trim_right(key);

				string val = sline.substr(pos + 1);
				trim_left(val);
				trim_right(val);
				item[key] = val;
			}
		}
	}
	m_doc[skey] = item;
}
const char* CConfig::getvalue(string elem, string key)
{
	if (elem.size() != 0 && key.size() != 0)
	{
		return (m_doc[elem])[key].c_str();
	}
	return NULL;
}

ELEMENT& CConfig::GetElement()
{
	return m_doc;
}

ITEM& CConfig::getItem(string item)
{
	return m_doc[item];
}

void CConfig::DebugPrintDoc()
{
	ELEMENT::iterator iterKey;
	ITEM::iterator iterValue;
	for (iterKey = m_doc.begin(); iterKey != m_doc.end(); iterKey++)
	{

		for (iterValue = (*iterKey).second.begin();
				iterValue != (*iterKey).second.end(); iterValue++)
				{

		}
	}
}
